package com.mwx.baselib.net;

import android.text.TextUtils;
import android.util.Log;

import com.mwx.baselib.utils.SPUtils;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;

public class HttpClient {
    private static final String TAG = "zb_music";
    private static volatile OkHttpClient instance; // 使用volatile关键字确保可见性

    private HttpClient() {
    } // 私有构造函数防止外部实例化

    public static OkHttpClient getInstance() {
        if (instance == null) { // 第一次检查
            synchronized (HttpClient.class) {
                if (instance == null) { // 第二次检查
                    instance = new OkHttpClient.Builder().retryOnConnectionFailure(true)
                            .addInterceptor(getHttpLoggingInterceptor())
                            .addInterceptor(getAuthInterceptor())
                            .build();
                }
            }
        }
        return instance;
    }

    private static HttpLoggingInterceptor getHttpLoggingInterceptor() {
        return new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                Log.i(TAG, JsonUtil.decodeUnicode(message));
            }
        }).setLevel(HttpLoggingInterceptor.Level.BODY);
    }

    private static Interceptor getAuthInterceptor() {
        return new Interceptor() {
            @Override
            public Response intercept(Interceptor.Chain chain) throws IOException {
                Request original = chain.request();
                if (!TextUtils.isEmpty((String) SPUtils.get(SPUtils.TOKEN,""))){
                    Request request = original.newBuilder()
                            .header("Authorization", "Bearer "+SPUtils.get(SPUtils.TOKEN,""))
                            .method(original.method(), original.body())
                            .build();
                    return chain.proceed(request);
                }
                return chain.proceed(original);
            }
        };
    }
}
